<script setup lang='ts'>
import AddSaleAttribute from './add-saleAttribute.vue'

const emits = defineEmits(['getDataStructure'])
// const props = withDefaults(defineProps<{
//     saleAttribute?: any
// }>(), {
//     saleAttribute: () => {},
// })
const saleAttribute = defineModel<any>('saleAttribute', { required: true })
const dataStructure = ref<any[]>([])
const currenLeftIndex = ref(0)
// const { saleAttribute } = toRefs(props)
const visible = ref<boolean>(false)

const saleAttributeName = ref<string>('')

function getRightIndex(index) {
    console.log(index, 'getRightIndex')
    currenLeftIndex.value = index
    console.log(saleAttribute.value[currenLeftIndex.value], 'saleAttribute')
}

function addSaleAttribute() {
    visible.value = true
    saleAttributeName.value = saleAttribute.value[currenLeftIndex.value]?.attributeName || ''
}

function delAttribute(index) {
    saleAttribute.value[currenLeftIndex.value]?.attributeValue.splice(index, 1)
    console.log(saleAttribute.value[currenLeftIndex.value]?.attributeValue, 'saleAttribute.attributeValue')
}

function getSaleAttribute(e) {
    saleAttribute.value[currenLeftIndex.value]?.attributeValue.push(e)
    console.log(saleAttribute.value[currenLeftIndex.value]?.attributeValue, 'saleAttribute.attributeValue')
}

function sure() {
    const combinations = getAllAttributeCombinations(saleAttribute.value).flat()
    const mergedDataMap = new Map()
    combinations.forEach((entry) => {
        const { attributeName, value } = entry
        // 如果已经存在该属性名称，则合并值
        if (mergedDataMap.has(attributeName)) {
            const existingSet = mergedDataMap.get(attributeName)
            existingSet.add(value)
        }
        else {
        // 否则，创建新的属性项
            mergedDataMap.set(attributeName, new Set([value]))
        }
    })
    const result = Array.from(mergedDataMap, ([attributeName, valueSet]) => ({
        attributeKey: attributeName,
        attributeValue: Array.from(valueSet).join(';'),
    }))
    dataStructure.value = generateDataStructure(saleAttribute.value)
    emits('getDataStructure', dataStructure.value, result)
}

function handleChange(e) {
    console.log(e, saleAttribute.value, 'handleChange')
}

// 生成数据结构
function generateDataStructure(attributes) {
    console.log(attributes, 'generateDataStructure')
    const attributeCombinations = getAllAttributeCombinations(attributes)
    console.log(attributeCombinations, 'generateDataStructure')
    const dataStructure = attributeCombinations.map((combination) => {
        const combinationName = combination.reduce((name, attr) => {
            return `${name}${attr.attributeName}:${attr.value};`
        }, '').slice(0, -1)
        return { id: '', productModel: '', skuAttributeInfo: combinationName, skuCount: 1, skuName: '', skuPrice: '', skuPriceIntroduce: '' }
    })
    return dataStructure
}

function getAllAttributeCombinations(attributes) {
    console.log(attributes, 'getAllAttributeCombinations')
    let combinations = [[]]
    attributes.forEach((attribute) => {
        if (attribute.flag) {
            // 如果 attributeValue 是空的，跳过当前属性，不破坏组合
            if (attribute.attributeValue.length === 0)
                return
            const validValues = attribute.attributeValue.filter(value => value.flag)
            if (validValues.length === 0)
                return
            const newCombinations: any = []
            attribute.attributeValue.forEach((value) => {
                if (value.flag) {
                    combinations.forEach((combination) => {
                        const newCombination = [...combination, { attributeName: attribute.attributeName, value: value.value }]
                        newCombinations.push(newCombination)
                    })
                }
            })
            combinations = newCombinations
        }
    })
    return combinations
}

// 获取所有属性组合
// function getAllAttributeCombinations(attributes) {
//     console.log(attributes, 'getAllAttributeCombinations')
//     let combinations = [[]]
//     attributes.forEach((attribute) => {
//         if (attribute.flag) {
//             // 如果 attributeValue 是空的，跳过当前属性，不破坏组合
//             if (attribute.attributeValue.length === 0)
//                 return
//             const newCombinations: any = []
//             attribute.attributeValue.forEach((value) => {
//                 if (value.flag) {
//                     combinations.forEach((combination) => {
//                         const newCombination = [...combination, { attributeName: attribute.attributeName, value: value.value }]
//                         newCombinations.push(newCombination)
//                     })
//                 }
//             })
//             combinations = newCombinations
//         }
//     })
//     return combinations
// }
</script>

<template>
    <div class="p-20 mt-20 bg-white border-px border-[var(--el-border-color)] border-solid">
        <div class="text-20 font-500">
            销售属性
        </div>

        <div class="my-20 bg-[var(--el-border-color)] h-1 w-full" />

        <div v-if="saleAttribute && saleAttribute.length > 0"
             class="sale-attribute-container"
        >
            <div class="left">
                <div>选择销售属性：</div>

                <el-scrollbar height="260"
                              class="left-checkbox-container"
                >
                    <div v-for="(item, index) in saleAttribute"
                         :key="item.id"
                         class="left-checkbox-item"
                         :class="currenLeftIndex === index ? 'bg-[var(--el-color-primary-light-9)]' : 'bg-white'"
                    >
                        <div class="flex">
                            <el-checkbox v-model="item.flag"
                                         size="small"
                                         @change="handleChange($event)"
                            />

                            <span class="pl10 cursor-pointer"
                                  @click="getRightIndex(index)"
                            >{{ item.attributeName }}</span>
                        </div>

                        <div i-material-symbols:play-arrow
                             class="size-20 transition"
                             :class="item.flag ? 'text-red' : 'text-gray-3'"
                        />
                    </div>
                </el-scrollbar>
            </div>

            <div class="right">
                <div>选择销售属性值：</div>

                <el-scrollbar height="260"
                              class="right-checkbox-container"
                >
                    <div class="right-checkbox-item">
                        <div v-for="(obj, index) in saleAttribute[currenLeftIndex].attributeValue"
                             :key="obj.id"
                             class="flex items-center"
                        >
                            <el-checkbox v-model="obj.flag"
                                         :label="obj.value"
                                         size="small"
                            />

                            <div v-if="obj.isCustomerAttribute"
                                 class="pl-10 text-orange-5 flex flex-none cursor-pointer"
                                 @click="delAttribute(index)"
                            >
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
        </div>

        <el-button v-if="saleAttribute && saleAttribute.length > 0"
                   type="primary"
                   class="mt-8"
                   @click="addSaleAttribute"
        >
            添加属性值
        </el-button>

        <el-button v-if="saleAttribute && saleAttribute.length > 0"
                   type="primary"
                   class="mt-8"
                   @click="sure"
        >
            生成SKU
        </el-button>
    </div>

    <AddSaleAttribute v-model:visible="visible"
                      v-model:saleAttributeName="saleAttributeName"
                      @get-sale-attribute="getSaleAttribute"
    />
</template>

<style lang="less" scoped>
.sale-attribute-container {
    width: 100%;
    height: 300px;
    border: 1px solid #dcdfe6;
    display: flex;
    .left {
        width: 30%;
        height: 100%;
        border-right: 1px solid #dcdfe6;
        padding: 10px;
        .left-checkbox-container {
            .left-checkbox-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }
    .right {
        flex: 1;
        padding: 10px;
        .right-checkbox-container {
            .right-checkbox-item {
            }
        }
    }
}
:deep(.el-tag) {
    background-color: #f7f7f7;
    color: #333;
    border-color: #f7f7f7;

    .el-tag__content {
        font-size: 14px;
        font-weight: 500;
    }

    .el-icon {
        color: var(--el-color-white);
        background-color: #bfbfbf;

        &:hover {
            background-color: #bfbfbf;
        }
    }
}

:deep(.el-checkbox) {
    // zoom: 120%;
    // width: 100%;

    .el-checkbox__label {
        color: #333;
        width: 100%;
    }
}
</style>
